package com.xykj.enterprise.wechat.core.eao;

import com.alibaba.fastjson.JSON;
import com.ydn.dbframe.plugin.activerecord.Page;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author zhouxu
 * @create 2021-02-26 10:07
 */
public abstract class BaseEao<T> {

    public Page<T> toPage(SearchResponse response, int pageNumber, int pageSize, Class<T> clazz) {
        Page<T> page = new Page<>();
        int count = (int) response.getHits().totalHits;
        page.setTotalPage((int) Math.ceil(count * 1.0 / pageSize));
        page.setTotalRow(count);
        page.setPageNumber(pageNumber);
        page.setPageSize(pageSize);
        List<T> list = new ArrayList<>();
        for (SearchHit hit : response.getHits()) {
            list.add(JSON.parseObject(JSON.toJSONString(hit.getSourceAsMap()), clazz));
        }
        page.setList(list);
        return page;
    }

}
